package edu.chen.interceptor;

import edu.chen.entity.User;
import edu.chen.service.LeaseService;
import edu.chen.service.UserService;
import edu.chen.util.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class loginInterceptor extends HandlerInterceptorAdapter{

    @Autowired
    private UserService userService;

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();



        Object user = httpServletRequest.getSession().getAttribute("loginUser") ;

        if(user != null){   //不为空说明此次会话刚登陆过
            return true;
        }

        /**
         * 设置只有一次,是因为在点击退出之后可以重新登录 而不是直接从cookie获取信息
         */
        //取出cookie
        Cookie cookie = new CookieUtils().getCookieByName(httpServletRequest, "autoLogin");
        System.out.println(cookie);
        //若不为空 则进行下一步处理
        if (cookie != null) {
            String data = cookie.getValue();
            String[] userData = data.split("#");        //username#password的字符串
            User user1 = userService.verifyLogin(userData[0], userData[1]);
            if (user1 != null) {
                //验证登录并将结果放在Session中 如果出错会直接抛出
                httpServletRequest.getSession().setAttribute(
                        "loginUser", user1);
                if (uri.endsWith("/loginView") || uri.endsWith("/login"))
                    httpServletResponse.sendRedirect("/library");
                return true;
            }
        }

        /**
         *  如果请求就是指向登录界面则直接放行 (查看书本信息不需要登录)
         *  uri.endsWith("/loginView") || uri.endsWith("/login") ||
         */
        if( uri.endsWith("/loginView") || uri.endsWith("/login")
                || uri.endsWith(".js") || uri.endsWith(".css")
                || uri.endsWith(".map") || uri.endsWith("/library")){
            return true;
        }




        /**
         * 若没有user信息,则表示没有登录 客户端跳转到登录界面
         */
        httpServletResponse.sendRedirect("/library/user/loginView");
        return false;
    }
}
